package com.geqian.file.storage;

import com.aliyun.oss.common.utils.IOUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.UUID;

/**
 * @author geqian
 * @date 0:51 2024/1/5
 */
public class LocalStorage implements FileStorageTemplate {

    @Value("${local-storage.file.save-path}")
    private String savePath;

    @Value("${local-storage.file.request.url-prefix}")
    private String requestUrl;

    @PostConstruct
    private void init() {
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }


    @Override
    public String uploadFile(byte[] bytes, String filename) {

        String uuid = UUID.randomUUID().toString().replace("-", "");

        filename = uuid + filename.substring(filename.lastIndexOf("."));

        try (FileOutputStream out = new FileOutputStream(new File(savePath + filename))) {

            out.write(bytes);

            return requestUrl + filename;

        } catch (Exception e) {
            throw new RuntimeException("文件上传失败！", e);
        }
    }

    @Override
    public String uploadFile(InputStream is, String filename) {
        try {
            byte[] bytes = IOUtils.readStreamAsByteArray(is);
            return uploadFile(bytes, filename);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败！", e);
        } finally {
            closeResource(is);
        }
    }


    @Override
    public void deleteFile(String url) {
        int indexOf = url.lastIndexOf("/");
        String filename = url.substring(indexOf);
        File file = new File(savePath + filename);
        if (file.exists()) {
            file.delete();
        }
    }

}
